import { createRouter, createWebHistory } from "vue-router";
import type { RouteRecordRaw } from "vue-router";
import { routes } from "./routes/base";
import { resetRouter } from "./utils/resetRouter";
import { useAppStore } from "@/stores/app";

// 自动导入modules下的路由
const modules = import.meta.glob("./modules/*.ts", { eager: true });
const routeModuleList: RouteRecordRaw[] = [];

Object.keys(modules).forEach((key) => {
  const mod = (modules[key] as any).default || {};
  const modList = Array.isArray(mod) ? [...mod] : [mod];
  routeModuleList.push(...modList);
});

const router = createRouter({
  history: createWebHistory(),
  routes: [...routes, ...routeModuleList],
});

router.beforeEach((to, from, next) => {
  console.log("路由跳转:", from.path, "→", to.path); // 确认是否触发
   if (to.matched.length === 0) {
    console.log("跳转到 404");
    next('/404') // 直接跳转且不返回
    return // 确保终止后续逻辑
  }
  // 方案二,方案三公用
  const appStore = useAppStore();
  appStore.setLoading(true); // 开始加载
  next(); // 必须调用 next() 否则路由会卡住
});

router.afterEach(() => {
  // 不需要手动处理，依赖方案2的自动检测
});

// 导出重置方法
export { resetRouter };
export default router;
